package intelligentCustomer.planning;

import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import intelligentCustomer.intent.Intent;
import intelligentCustomer.session.UserSession;
import intelligentCustomer.reasoning.ReasoningEngine;

import java.util.*;

/**
 * 自适应规划器
 * 基于执行反馈动态调整计划
 */
public class AdaptivePlanner {
    private final OpenAiStreamingChatModel model;
    private final Map<String, Double> stepSuccessRates = new HashMap<>();
    private static final int MAX_RETRIES = 3;
    
    public AdaptivePlanner(OpenAiStreamingChatModel model) {
        this.model = model;
    }
    
    /**
     * 创建并执行自适应计划
     */
    public PlanResult executePlan(String query, Intent intent, UserSession session) {
        PlanningContext context = new PlanningContext(query, intent, session);
        Plan plan = createInitialPlan(context);
        
        return executePlan(plan, context);
    }
    
    /**
     * 执行给定的计划
     */
    public PlanResult executePlan(Plan plan, PlanningContext context) {
        StringBuilder executionLog = new StringBuilder();
        Map<String, String> results = new HashMap<>();
        boolean successful = true;
        
        while (plan.hasMoreSteps() && !context.hasExceededMaxAttempts()) {
            // 执行当前步骤
            PlanStep step = plan.getNextStep();
            executionLog.append("执行步骤: ").append(step.getName()).append("\n");
            
            try {
                // 执行步骤
                String result = step.execute(context);
                executionLog.append("步骤结果: 成功\n");
                
                // 保存结果
                results.put(step.getName(), result);
                context.addResult(step.getName(), result);
                
                // 评估结果
                FeedbackResult feedback = evaluateExecution(
                    new StepResult(true, result, step.getName()), 
                    context
                );
                
                // 如果结果不满意，调整计划
                if (!feedback.isSuccessful()) {
                    executionLog.append("结果评估: 不满意, 原因: ").append(feedback.getReason()).append("\n");
                    
                    // 根据反馈调整计划
                    if (context.getRetryCount(step.getName()) < MAX_RETRIES) {
                        context.incrementRetryCount(step.getName());
                        step.adjustParameters(context);
                        plan.retryCurrentStep();
                        executionLog.append("操作: 重试步骤\n");
                    } else {
                        executionLog.append("操作: 超过最大重试次数，继续执行\n");
                    }
                } else {
                    executionLog.append("结果评估: 满意\n");
                }
                
            } catch (Exception e) {
                executionLog.append("步骤结果: 失败, 错误: ").append(e.getMessage()).append("\n");
                e.printStackTrace();
                // 处理失败
                if (context.getRetryCount(step.getName()) < MAX_RETRIES) {
                    context.incrementRetryCount(step.getName());
                    step.adjustParameters(context);
                    plan.retryCurrentStep();
                    executionLog.append("操作: 重试步骤\n");
                } else {
                    executionLog.append("操作: 超过最大重试次数，标记为失败\n");
                    successful = false;
                    break;
                }
            }
            
            context.incrementAttempts();
        }
        
        // 保存执行日志
        context.setAttribute("executionLog", executionLog.toString());
        
        return new PlanResult(results, successful, executionLog.toString());
    }
    
    /**
     * 创建初始计划
     */
    private Plan createInitialPlan(PlanningContext context) {
        Plan plan = new Plan();
        
        // 基于意图选择最优步骤序列
        switch (context.getIntent().getCategory()) {
            case "产品咨询":
                plan.addStep(new AnalysisStep("需求分析", model));
                plan.addStep(new SearchStep("产品搜索", model));
                plan.addStep(new ComparisonStep("特性对比", model));
                plan.addStep(new RecommendationStep("生成建议", model));
                break;
                
            case "售后服务":
                plan.addStep(new AnalysisStep("问题分析", model));
                plan.addStep(new SearchStep("解决方案搜索", model));
                plan.addStep(new RecommendationStep("操作指导", model));
                break;
                
            case "订单查询":
                plan.addStep(new SearchStep("订单搜索", model));
                plan.addStep(new AnalysisStep("状态分析", model));
                plan.addStep(new RecommendationStep("后续建议", model));
                break;
                
            default:
                plan.addStep(new AnalysisStep("通用分析", model));
                plan.addStep(new RecommendationStep("生成回复", model));
        }
        
        return plan;
    }
    
    /**
     * 创建基于推理的计划
     */
    public Plan createReasoningBasedPlan(PlanningContext context, ReasoningEngine reasoningEngine) {
        Plan plan = new Plan();
        
        // 根据意图类别创建不同的推理步骤
        switch (context.getIntent().getCategory()) {
            case "product_inquiry":
                plan.addStep(new ReasoningBasedPlanStep("需求分析推理", reasoningEngine, "需求分析"));
                plan.addStep(new ReasoningBasedPlanStep("产品匹配推理", reasoningEngine, "产品匹配"));
                plan.addStep(new ReasoningBasedPlanStep("比较推理", reasoningEngine, "比较分析"));
                plan.addStep(new ReasoningBasedPlanStep("推荐推理", reasoningEngine, "推荐生成"));
                break;
                
            case "refund":
                plan.addStep(new ReasoningBasedPlanStep("问题诊断推理", reasoningEngine, "问题诊断"));
                plan.addStep(new ReasoningBasedPlanStep("解决方案推理", reasoningEngine, "解决方案生成"));
                plan.addStep(new ReasoningBasedPlanStep("验证推理", reasoningEngine, "方案验证"));
                break;
                
            case "order_status":
                plan.addStep(new ReasoningBasedPlanStep("订单检索推理", reasoningEngine, "订单检索"));
                plan.addStep(new ReasoningBasedPlanStep("状态分析推理", reasoningEngine, "状态分析"));
                plan.addStep(new ReasoningBasedPlanStep("行动建议推理", reasoningEngine, "行动建议"));
                break;
                
            default:
                // 默认推理步骤
                plan.addStep(new ReasoningBasedPlanStep("通用推理", reasoningEngine, "通用分析"));
                plan.addStep(new ReasoningBasedPlanStep("回复生成推理", reasoningEngine, "回复生成"));
        }
        
        return plan;
    }
    
    /**
     * 评估执行结果
     */
    private FeedbackResult evaluateExecution(StepResult result, PlanningContext context) {
        if (!result.isSuccessful()) {
            return new FeedbackResult(false, "执行失败", FeedbackType.RETRY_NEEDED);
        }
        
        // 简单评估 - 实际系统中可以使用更复杂的评估逻辑
        String stepResult = result.getResult();
        if (stepResult == null || stepResult.isEmpty()) {
            return new FeedbackResult(false, "结果为空", FeedbackType.RETRY_NEEDED);
        }
        
        if (stepResult.length() < 10) {
            return new FeedbackResult(false, "结果过短", FeedbackType.RETRY_NEEDED);
        }
        
        // 使用模型评估结果质量
        String evaluation = ReasonGenerator.generate(model,"评估以下结果质量:\n" + stepResult);
        String reason = extractReason(evaluation);
        String suggestion = extractSuggestion(evaluation);  // 使用extractSuggestion方法
        
        boolean satisfactory = !evaluation.contains("不满意") && 
                              !evaluation.contains("不足") && 
                              !evaluation.contains("不够");
        
        // 更新步骤成功率统计
        updateStepStatistics(result);
        
        return new FeedbackResult(satisfactory, 
            reason,
            satisfactory ? FeedbackType.SUCCESS : FeedbackType.ADJUSTMENT_NEEDED,
            suggestion);  // 使用提取的建议
    }
    
    /**
     * 更新步骤统计信息
     */
    private void updateStepStatistics(StepResult result) {
        String stepName = result.getStepName();
        double currentRate = stepSuccessRates.getOrDefault(stepName, 1.0);
        double newRate = result.isSuccessful() ? 
            currentRate * 0.9 + 0.1 : currentRate * 0.9;
        stepSuccessRates.put(stepName, newRate);
    }
    
    /**
     * 从评估结果中提取原因
     */
    private String extractReason(String evaluation) {
        // 简化实现
        if (evaluation.contains("原因:")) {
            int start = evaluation.indexOf("原因:") + 3;
            int end = evaluation.indexOf("\n", start);
            if (end == -1) end = evaluation.length();
            return evaluation.substring(start, end).trim();
        }
        return "未提供具体原因";
    }
    
    /**
     * 从评估结果中提取建议
     */
    private String extractSuggestion(String evaluation) {
        // 简化实现
        if (evaluation.contains("建议:")) {
            int start = evaluation.indexOf("建议:") + 3;
            int end = evaluation.indexOf("\n", start);
            if (end == -1) end = evaluation.length();
            return evaluation.substring(start, end).trim();
        }
        return "未提供具体建议";
    }

} 